package com.vocabulary.controller;

import com.vocabulary.dto.ArticleEstimateDto;
import org.example.EstimateResult;
import org.example.VocabEstimator;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api/article")
@CrossOrigin(origins = "*")
public class ArticleController {

    @PostMapping("/estimate")
    public ResponseEntity<ArticleEstimateDto> estimateArticleVocabulary(@RequestParam("file") MultipartFile file) {
        try {
            // 创建临时文件
            String fileName = file.getOriginalFilename();
            Path tempFile = Files.createTempFile("article_", "_" + fileName);
            file.transferTo(tempFile.toFile());

            // 调用文章词汇量估算算法
            EstimateResult result = VocabEstimator.estimate(tempFile.toFile());

            // 转换结果到DTO
            ArticleEstimateDto dto = new ArticleEstimateDto(
                result.level,
                result.vocabSize,
                result.confidence,
                result.levelHits
            );

            // 删除临时文件
            Files.deleteIfExists(tempFile);

            return ResponseEntity.ok(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/estimate-text")
    public ResponseEntity<ArticleEstimateDto> estimateTextVocabulary(@RequestBody String text) {
        try {
            // 创建临时文件
            Path tempFile = Files.createTempFile("text_", ".txt");
            Files.write(tempFile, text.getBytes());

            // 调用文章词汇量估算算法
            EstimateResult result = VocabEstimator.estimate(tempFile.toFile());

            // 转换结果到DTO
            ArticleEstimateDto dto = new ArticleEstimateDto(
                result.level,
                result.vocabSize,
                result.confidence,
                result.levelHits
            );

            // 删除临时文件
            Files.deleteIfExists(tempFile);

            return ResponseEntity.ok(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
} 